from fastapi import APIRouter, Query
from tortoise.expressions import Q
from app.controllers.system.dept import dept_controller
from app.schemas.base import Success, SuccessExtra
from app.schemas.depts import *

dept_router = APIRouter()


@dept_router.get("/list", summary="查看部门列表")
async def list_dept(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    name: str = Query(None, description="部门名称"),
):
    q = Q()
    if name:
        q = Q(name__contains=name)
    total, role_objs = await dept_controller.list(page=page, page_size=page_size, search=q)
    data = [await obj.to_dict() for obj in role_objs]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)



@dept_router.get("/get", summary="查看部门")
async def get_dept(
    id: int = Query(..., description="部门ID"),
):
    dept_obj = await dept_controller.get(id=id)
    data = await dept_obj.to_dict()
    return Success(data=data)


@dept_router.post("/create", summary="创建部门")
async def create_dept(
    dept_in: DeptCreate,
):
    await dept_controller.create_dept(obj_in=dept_in)
    return Success(msg="Created Successfully")


@dept_router.post("/update", summary="更新部门")
async def update_dept(
    dept_in: DeptUpdate,
):
    await dept_controller.update_dept(obj_in=dept_in)
    return Success(msg="Update Successfully")


@dept_router.delete("/delete", summary="删除部门")
async def delete_dept(
    dept_id: int = Query(..., description="部门ID"),
):
    await dept_controller.delete_dept(dept_id=dept_id)
    return Success(msg="Deleted Success")

@dept_router.get("/tree", summary="树形部门")
async def tree_dept():
    data = await dept_controller.get_dept_tree()
    datas = [{
        "id": 0,
        "name": "全部",
        "desc": "全部",
        "order": 1,
        "parent_id": -1,
        "children": data,  # 递归构建子部门
    }]
    return SuccessExtra(data=datas)
